package app;


import com.opensymphony.xwork2.ActionSupport;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


// This is the first Action that will execute upon application entry.
// Its job is to create the database and data table the example
// report will report against.  It then forwards to the JSP where
// the user can enter report parameters.
public class ParameterEntryAction extends ActionSupport {


  public String execute() throws Exception {

    // Open connection to database.  Will create it if it doesn't yet exist.
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    dataSource.setUrl("jdbc:derby:dvplugin;create=true");
    dataSource.setUsername("");
    dataSource.setPassword("");

    // Drop table in case it exists and recreate it.
    System.out.println("Creating and populating database");
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    try {
      jdbcTemplate.execute("DROP TABLE dvplugintable");
    } catch (Exception e) {
      // Eat this Exception because it almost certainly means the table
      // doesn't exist, which means the DROP caused an exception.  If this
      // isn't the cause, then... err, well, uhh, umm, WHATEVER!
    }
    jdbcTemplate.execute(
      "CREATE TABLE dvplugintable ( " +
      "firstname VARCHAR(50), " +
      "lastname VARCHAR(50), " +
      "age BIGINT " +
      ")"
    );
    // Now populate the table with some test data.
    jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("INSERT INTO dvplugintable " +
      "(firstname,lastname,age) VALUES ('frank','zammetti',34)");
    jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("INSERT INTO dvplugintable " +
      "(firstname,lastname,age) VALUES ('billy','joel',59)");
    jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("INSERT INTO dvplugintable " +
      "(firstname,lastname,age) VALUES ('britney','spears',24)");
    jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("INSERT INTO dvplugintable " +
      "(firstname,lastname,age) VALUES ('jessica','alba',23)");
    // Now read the data back to be sure it worked.
    List data = jdbcTemplate.queryForList("SELECT firstname,lastname,age " +
      "FROM dvplugintable");
    for (Iterator it = data.iterator(); it.hasNext();) {
      Map m = (Map)it.next();
      System.out.println("firstname=" + (String)m.get("FIRSTNAME") +
        ", lastname=" + (String)m.get("LASTNAME") + ", age=" + m.get("AGE"));
    }
    System.out.println("Done");

    return SUCCESS;

  } // End execute().


} // End class.
